import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
});
//request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.token = store.getters.token;
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

//response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code != 200) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 2 * 1000
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    Message({
      message: error,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(new Error("Error"));
  }
);
export default service;
